<template>
  <view class="swiperImage" style="padding: 0 29rpx">
    <swiper
      class="swiperImage-container"
      circular
      :indicator-dots="indicatorDots"
      :autoplay="autoplay"
      :interval="interval"
      :duration="duration"
      :current="swiperIndex"
      @change="onChange"
    >
      <swiper-item
        class="swiperItem"
        v-for="(item, index) in swiperData"
        :key="index"
      >
        <canvas
          style="height: 431rpx; width: 100%"
          :canvas-id="'secondCanvas' + index"
          :id="'secondCanvas' + index"
          @click="canvasClickHandle"
        ></canvas>
      </swiper-item>
    </swiper>

    <!-- <z-swiper
      ref="zSwiper"
      class="swiperImage-container"
      v-model="swiperData"
      :options="options"
      @slideChange="onChange"
    >
      <z-swiper-item
        class="swiperItem"
        v-for="(item, index) in swiperData"
        :key="index"
      > -->
    <!-- <image
          ref="img"
          class="imageStyle"
          :src="item.originImage"
          mode="aspectFit"
        >
        </image> -->

    <!-- <canvas
          style="height: 431rpx; width: 100%"
          :canvas-id="'secondCanvas' + index"
          :id="'secondCanvas' + index"
          @touchend="canvasClickHandle"
        ></canvas>
      </z-swiper-item>
    </z-swiper> -->
    <scroll-view style="height: 0; width: 0">
      <view class="hideCanvass">
        <canvas
          hidpi
          canvas-id="previewImage"
          id="previewImage"
          :style="{
            height: sourceImageHeight + 'px',
            width: sourceImageWidth + 'px'
          }"
        ></canvas>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import Vue from "vue";
export default Vue.extend({
  name: "canvasSwiper",
  props: ["swiperData", "boxSwitch", "postUrl", "threshold"],
  data() {
    return {
      options: {
        centeredSlides: true,
        // centeredSlidesBounds: true,
        spaceBetween: 14,
        slidesPerView: 1.15
      },
      swiperIndex: 0,
      indicatorDots: false,
      autoplay: false,
      interval: 2000,
      duration: 500,
      canvasInfo: {},
      sourceImageWidth: 1440,
      sourceImageHeight: 900,
      canvasControlComponentH: 0,
      selfContainerW: 0
      // tempImage: ""
    };
  },
  mounted() {
    this.$nextTick(async () => {
      const query = uni.createSelectorQuery();
      query.select("#canvasControl").boundingClientRect((data) => {
        this.canvasControlComponentH = data.height;
      });

      query
        .in(this)
        .select(".swiperImage")
        .boundingClientRect((data) => {
          this.selfContainerW = data.width;
        })
        .exec();

      // #ifdef H5
      if (this.swiperData.length > 0) {
        let { width, height } = await this.queryCanvasInfo("0");
        this.canvasInfo = { width: width, height };
        this.swiperData.forEach((ele, index) => {
          this.$emit("collectData", {
            dataList: JSON.parse(ele.originData),
            index
          });
          ele["originImage"] = ele.image;
          this.drawImage(ele.iamge, index, this.swiperData[index]);
        });
      }
      // #endif
    });
  },
  methods: {
    onChange(i) {
      // this.swiperIndex = this.$refs.zSwiper.swiper.activeIndex;
      this.swiperIndex = i.detail.current;
      this.$emit("swiperDataIndex", this.swiperIndex);
      this.$emit("selectIndex", 0);
      if (this.swiperData[this.swiperIndex].data.length > 0) {
        this.drawImage(
          this.swiperData[this.swiperIndex].originImage,
          this.swiperIndex,
          this.swiperData[this.swiperIndex]
        );
      }
    },
    zoomImage(imageTarget, canvasTarget) {
      if (imageTarget.height > imageTarget.width) {
        return {
          width: (imageTarget.width / imageTarget.height) * canvasTarget.height,
          height: canvasTarget.height,
          x:
            canvasTarget.width / 2 -
            ((imageTarget.width / imageTarget.height) * canvasTarget.height) /
              2,
          y: 0
        };
      }
      return {
        width: canvasTarget.width,
        height: canvasTarget.height,
        x: 0,
        y: 0
      };
    },
    async queryCanvasInfo(id) {
      return new Promise((resolve, reject) => {
        const query = uni.createSelectorQuery().in(this);
        query
          .select("#secondCanvas" + id)
          .boundingClientRect((data) => {
            resolve(data);
          })
          .exec();
      });
    },
    async drawImage(image, index, item) {
      let ctx = uni.createCanvasContext("secondCanvas" + index, this);
      this.sourceImageWidth = item.width;
      this.sourceImageHeight = item.height;
      let { width, height, x, y } = this.zoomImage(
        {
          width: item.width,
          height: item.height
        },
        this.canvasInfo
      );
      ctx.drawImage(item.originImage, x, y, width, height);
      if (!this.boxSwitch) {
        ctx.draw();
        return false;
      }
      if (this.swiperData[this.swiperIndex].data.length === 0) {
        ctx.draw(true, () => {
          this.postApi(ctx, index, item);
        });
      } else {
        this.drawBox(ctx, this.swiperData[this.swiperIndex].data);
      }
    },
    drawBox(ctx, data, appoint = 0, previewImage = false) {
      let xZoom = 1;
      let yZoom = 1;
      let color = "#0AB679";
      let selectColor = "#0091FF";
      let abnormalColor = "#D53939";
      let fontSize = 15;
      ctx.lineWidth = 3;
      ctx.setFillStyle("#ffffff");
      ctx.setFontSize(fontSize);
      ctx.setTextBaseline("top");
      ctx.shadowColor = "#333";
      ctx.shadowBlur = 2;
      ctx.shadowOffsetX = 2;
      let { width, height, x, y } = this.zoomImage(
        {
          width: this.sourceImageWidth,
          height: this.sourceImageHeight
        },
        this.canvasInfo
      );
      if (!previewImage) {
        ctx.lineWidth = 1;
        xZoom = width / this.sourceImageWidth;
        yZoom = height / this.sourceImageHeight;
        fontSize = 7;
        ctx.setFontSize(fontSize);
      } else {
        // ctx.setFontSize(15);
        x = 0;
      }
      data.forEach((element, index) => {
        let x1 = element.position[0] * xZoom;
        let y1 = element.position[1] * yZoom;
        let xW = (element.position[2] - element.position[0]) * xZoom;
        let yH = (element.position[3] - element.position[1]) * yZoom;
        if ("type" in element) {
          ctx.setStrokeStyle(appoint === index ? selectColor : abnormalColor);
        } else {
          ctx.setStrokeStyle(appoint === index ? selectColor : color);
        }
        if ("name" in element) {
          let text =
            element.name === "image_vag" || element.name === "image_vague"
              ? "未入库"
              : element.name;
          if (yH / xW < 2) {
            // if(element.s)
            if (getCurrentPages()[0].route === "pages/inventory/index") {
              let score = element.score;
              if (score >= 0.2 && score <= 0.5) {
                fontSize = yH / 2.6 > fontSize ? fontSize : yH / 2.8;
                ctx.setFontSize(fontSize);
                ctx.fillText("疑似", x1 + x + 2, y1, xW - 5);
                ctx.fillText(text, x1 + x + 2, y1 + fontSize, xW - 5);
              } else {
                ctx.fillText(text, x1 + x + 2, y1, xW - 5);
              }
            } else {
              ctx.fillText(text, x1 + x + 2, y1, xW - 5);
            }
          } else {
            this.lengthways(ctx, text, x1 + x, y1, xW, yH);
          }

          // #405680
        }
        ctx.strokeRect(x1 + x, y1, xW, yH);
      });
      if (!previewImage) ctx.draw();
    },
    lengthways(ctx, text, x, y, xW, yH) {
      let textArr = text.split("");
      let fontSize = xW / 3;
      let maxSize = yH / textArr.length;
      for (let i = 0; i < textArr.length; i++) {
        ctx.setFontSize(fontSize);
        ctx.fillText(textArr[i], x + 4, y + i * fontSize, maxSize);
      }
    },
    postApi(ctx, index, item) {
      uni.showLoading({
        title: "识别中",
        mask: true
      });
      let image = item.image.split("data:image/jpeg;base64,")[1];
      uni.request({
        url: this.postUrl,
        method: "POST",
        data: {
          image: image,
          image_type: 1,
          threshold: this.threshold
        },
        header: {},
        success: (res) => {
          let dataList = JSON.parse(res.data.data);
          this.$emit("swiperData", { index, dataList });
          this.$emit("collectData", {
            dataList,
            index
          });
          setTimeout(() => {
            this.drawImage(
              item.originImage,
              index,
              this.swiperData[this.swiperIndex]
            );
            uni.hideLoading();
          }, 500);
        }
      });
    },
    canvasClickHandle(event) {
      // let { x, y } = event.changedTouches[0];
      let x =
        event.changedTouches[0].clientX -
        (this.selfContainerW - this.canvasInfo.width) / 2;
      let y = event.changedTouches[0].clientY - this.canvasControlComponentH;

      let zoomImage = this.zoomImage(
        {
          width: this.sourceImageWidth,
          height: this.sourceImageHeight
        },
        this.canvasInfo
      );
      let xZoom = zoomImage.width / this.sourceImageWidth;
      let yZoom = zoomImage.height / this.sourceImageHeight;
      let forData = this.swiperData[this.swiperIndex].data;
      let ctx = uni.createCanvasContext(
        "secondCanvas" + this.swiperIndex,
        this
      );
      for (let i = 0; i < forData.length; i++) {
        let element = forData[i];
        let x1 = element.position[0] * xZoom + zoomImage.x;
        let y1 = element.position[1] * yZoom;
        let x2 = (element.position[2] - element.position[0]) * xZoom;
        let y2 = (element.position[3] - element.position[1]) * yZoom;
        // let nextX1 = forData[i + 1].position[0] * xZoom;
        // let nextX2 =
        //   (forData[i + 1].position[2] - forData[i + 1].position[0]) * xZoom;
        if (x >= x1 && x <= x2 + x1 && y >= y1 && y <= y2 + y1) {
          // if (x < nextX1 && x > nextX2) {
          ctx.drawImage(
            this.swiperData[this.swiperIndex].originImage,
            zoomImage.x,
            0,
            zoomImage.width,
            zoomImage.height
          );
          this.$emit("selectIndex", i);
          this.drawBox(ctx, forData, i);
          return false;
          // }

          // return false;
        }
      }
    },

    async onFullScreen(appoint = 0) {
      return new Promise((resolve) => {
        let currData = this.swiperData[this.swiperIndex];
        let ctx = uni.createCanvasContext("previewImage", this);
        ctx.drawImage(
          currData.originImage,
          0,
          0,
          currData.width,
          currData.height
        );
        this.drawBox(ctx, currData.data, 0, true);
        ctx.draw(true, () => {
          uni.canvasToTempFilePath(
            {
              x: 0,
              y: 0,
              width: this.sourceImageWidth,
              height: this.sourceImageHeight,
              destWidth: this.sourceImageWidth,
              destHeight: this.sourceImageHeight,
              fileType: "jpg",
              canvasId: "previewImage",
              success: (res) => {
                // 在H5平台下，tempFilePath 为 base64
                // that.imagesrc = res.tempFilePath;
                resolve(res.tempFilePath);
              }
            },
            this
          );
        });
      });
    }
  },
  watch: {
    swiperData(newVal, oldVal) {
      let last = newVal.length - 1;
      if (newVal[last].data.length > 0) return false;
      this.$nextTick(async () => {
        this.swiperIndex = last;
        let { width, height } = await this.queryCanvasInfo(last);
        this.canvasInfo = { width: width, height };
        this.drawImage(newVal[last].originImage, last, newVal[last]);

        // setTimeout(() => {
        //   console.log(this.$refs.zSwiper);
        //   if (newVal.length > 1)
        // this.$refs.zSwiper.swiper.slideTo(last, 500, false);
        // }, 500);
        // this.options.initialSlide = last
      });
    },
    boxSwitch(newVal) {
      // console.log(this.swiperIndex, this.swiperIndex);
      // this.swiperIndex[this.swiperIndex].data;
      this.drawImage(
        this.swiperData[this.swiperIndex].originImage,
        this.swiperIndex,
        this.swiperData[this.swiperIndex]
      );
    }
  }
});
</script>

<style lang="scss" scoped>
.swiperImage {
  &-container {
    height: 431rpx;
    width: 100%;
    .swiperItem {
      position: relative;
    }
    .imageStyle {
      width: 1024px;
      height: 720px;
    }
    canvas {
    }
  }
}
.hideCanvass {
  width: 0;
  height: 0;
  overflow: hidden;
}
</style>
